#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2021-1-1 23:09
# @file     : fund.py
# @Software : PyCharm
# ======================================#
import re
import json
import sys
from collections import defaultdict

import requests
from src.utils import parse_fund_table_xml, collect_gp_info, collect_zq_info, collect_fund_info, get_year, \
    print_classify_detail, print_fund_info, out_fund_all_up, out_fund_down_down_up


class Fund:
    def __init__(self):
        self.base_url = "http://fund.eastmoney.com"
        self.collect = {"Fund": defaultdict(dict), "GP": defaultdict(dict), "ZQ": defaultdict(dict)}

    def all_fund(self):
        """基金"""
        url = f"{self.base_url}/js/fundcode_search.js"
        fund_info = requests.get(url)
        if fund_info.status_code == 200:
            re_pattern = re.compile(r"\[\[(.*?)\]\]")
            fund_str = '{"fund_info":' + f"[[{re_pattern.findall(fund_info.text)[0]}]]" + "}"
            fund_dict = json.loads(fund_str)
            return fund_dict.get("fund_info")
        return []

    def fund_company(self):
        """基金公司"""
        url = f"{self.base_url}"
        company_info = requests.get(url)
        if company_info.status_code == 200:
            re_pattern = re.compile(r"{(.*?)}")
            company_str = "{" + re_pattern.findall(company_info.text)[0] + "}"
            company_dict = json.loads(company_str)
            return company_dict.get("op")
        return []

    def fund_ALL(self, top=25, skip=True, print=False):
        """前50个盈利最高的基金"""
        url = f"{self.base_url}/jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_GP(self, top=20, skip=True, print=False):
        """股票型盈利最高的20个"""
        url = f"{self.base_url}/GP_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_LOF(self, top=15, skip=True, print=False):
        """LOF理财类最高的"""
        url = f"{self.base_url}/LOF_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_HH(self, top=15, skip=True, print=False):
        """混合类最高的"""
        url = f"{self.base_url}/HH_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_ZQ(self, top=15, skip=True, print=False):
        """债券型"""
        url = f"{self.base_url}/ZQ_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_ZS(self, top=15, skip=True, print=False):
        """指数型"""
        url = f"{self.base_url}/ZS_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_ETF(self, top=15, skip=True, print=False):
        """ETF连接"""
        url = f"{self.base_url}/LJ_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)
            return data_list
        return []

    def fund_QDII(self, top=15, skip=True, print=False):
        url = f"{self.base_url}/QDII_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)

            return data_list
        return []

    def fund_FOF(self, top=15, skip=True, print=False):
        """FOF"""
        url = f"{self.base_url}/FOF_jzzzl.html"
        result = requests.get(url)
        if result.status_code == 200:
            data_list = parse_fund_table_xml(result.content, top, self.collect["Fund"], sys._getframe().f_code.co_name,
                                             print=print)
            if not skip:
                self.collect_fund_detail(data_list)

            return data_list
        return []

    def collect_fund_detail(self, code_list):
        for code in code_list:
            self.fund_info(code[0])

    def output_classify_detail(self):
        """输出信息：基金，股票，债券"""
        print_classify_detail(self.collect)

    def fund_info(self, code, output=False, name=None, ):
        url = f"{self.base_url}/{code}.html?spm=search"
        result = requests.get(url)
        f_info = g_info = z_info = defaultdict(dict)
        if result.status_code == 200:
            f_info = collect_fund_info(result.content.decode("utf-8"), self.collect["Fund"][code])

        url_gp = f"http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code={code}&topline=10"
        g_info = collect_gp_info(url_gp, self.collect["GP"], year=get_year())

        url_zq = f"http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=zqcc&code={code}"
        result_zq = requests.get(url_zq)
        if result_zq.status_code == 200:
            z_info = collect_zq_info(result_zq.content.decode("utf-8"), self.collect["ZQ"])

        if output:
            print_fund_info(code, name, f_info, g_info, z_info)

        return f_info, g_info, z_info

    def get_all_fund_increate_down_info(self, pn=10000):
        """pn: page number"""

        def get_float(value):
            num = None
            try:
                num = float(value)
            except:
                pass
            return num

        url = f"{self.base_url}/data/FundGuideapi.aspx?dt=4&sd=&ed=&st=asc&pi=1&pn={pn}&zf=diy&sh=list"
        fund_info = requests.get(url)
        collect = defaultdict(list)
        if fund_info.status_code == 200:
            re_pattern = re.compile(r':\["(.*?)\"],')
            fund_str = re_pattern.findall(fund_info.text)[0]
            fund_list = fund_str.split('","')
            # code name py 指数 今年以来 一周 一月 三月 一年 二年 三年
            for fund_s in fund_list:
                code, name, _, _, last_year1, week1, month1, month3, month6, year1, year2, year3 = fund_s.split(",")[
                                                                                                   0:12]
                week = get_float(week1)
                m1 = get_float(month1)
                m3 = get_float(month3)
                m6 = get_float(month6)
                y1 = get_float(year1)
                y2 = get_float(year2)
                y3 = get_float(year3)
                if week and week != "-":
                    # fund = [f"w1={round(week, 2)}"]
                    fund = [round(week, 2)]
                else:
                    # fund= [f"w1=0"]
                    fund=[0]
                    week=0
                if m1:
                    wm1 = m1 - week
                    # fund.append(f"m1={round(wm1,2)}")
                    fund.append(round(wm1, 2))
                if m3:
                    wm3 = m3 - m1
                    # fund.append(f"m3={round(wm3,2)}")
                    fund.append(round(wm3, 2))
                if m6:
                    wm6 = m6 - m3
                    # fund.append(f"m6={round(wm6, 2)}")
                    fund.append(round(wm6, 2))
                if y1:
                    my1 = y1 - m6
                    # fund.append(f"y1={round(my1, 2)}")
                    fund.append(round(my1, 2))
                if y2:
                    my2 = y2 - y1
                    # fund.append(f"y2={round(my2, 2)}")
                    fund.append(round(my2, 2))
                if y3:
                    my3 = y3 - y2
                    # fund.append(f"y3={round(my3, 2)}")
                    fund.append(round(my3, 2))

                collect[f"{code}:{name}"] = fund.copy()
        return collect



if __name__ == "__main__":
    f = Fund()
    # f.fund_info("160643", True)
    # f.fund_GP(top=2)
    # f.collect_fund_detail([["002190"]])
    f.get_fund_increate_info()
